package com.platform.system.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.platform.common.enums.UserTypeEnum;
import com.platform.common.utils.file.minio.FileEnum;
import com.platform.common.utils.file.minio.MinioFileUtils;
import com.platform.common.utils.spring.RequestHolder;
import com.platform.common.utils.uuid.UUID;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.platform.common.constant.HttpStatus;
import com.platform.common.core.domain.model.LoginUser;
import com.platform.common.core.page.TableDataInfo;
import com.platform.common.enums.ResultEnum;
import com.platform.common.exception.BusinessException;
import com.platform.common.utils.SecurityUtils;
import com.platform.common.utils.bean.BeanUtils;
import com.platform.common.utils.file.FileUtils;
import com.platform.common.utils.file.minio.CosClientConfigMap;
import com.platform.common.utils.uuid.SnowflakeIdWorker;
import com.platform.system.domain.dto.FileOperationDto;
import com.platform.system.domain.entity.device.WebUserInfo;
import com.platform.system.domain.vo.FileOperationVo;
import com.platform.system.service.ISysFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.platform.system.mapper.system.FileOperationMapper;
import com.platform.system.domain.entity.system.FileOperation;
import org.springframework.web.multipart.support.RequestPartServletServerHttpRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * @author Huangkai
 */
@Service
@Slf4j
public class SysFileServiceImpl extends ServiceImpl<FileOperationMapper, FileOperation> implements ISysFileService {

    @Autowired
    private ISysFileService sysFileService;

    @Resource
    private FileOperationMapper fileMapper;


    @Value("${spring.minio.localSavePath:''}")
    String localSavePath;

    @Resource
    MinioFileUtils minioFileUtils;

    @Resource
    CosClientConfigMap cosClientConfigMap;

    @Override
    public TableDataInfo selectFileList(FileOperationVo fileOperationVo) {
        LambdaQueryWrapper<FileOperation> fileLambdaQueryWrapper = new QueryWrapper<FileOperation>().lambda();
        fileLambdaQueryWrapper.eq(fileOperationVo.getName() != null, FileOperation::getName, fileOperationVo.getName());
        fileLambdaQueryWrapper.orderByDesc(FileOperation::getCreateTime);
        Page<FileOperation> page = new Page<>();
        page.setCurrent(fileOperationVo.getPageNum());
        page.setSize(fileOperationVo.getPageSize());
        IPage<FileOperation> fileIPage = fileMapper.selectPage(page, fileLambdaQueryWrapper);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        List<FileOperationDto> fileDtoList = new ArrayList<>();
        if(fileIPage.getRecords() != null && fileIPage.getRecords().size() > 0){
            List<FileOperation> fileList = fileIPage.getRecords();
            fileList.forEach(file -> {
                FileOperationDto fileDto = new FileOperationDto();
                String url = cosClientConfigMap.getDomain() + file.getFileKey();
                fileDto.setUrl(url);
                BeanUtils.copyProperties(file, fileDto);
                fileDtoList.add(fileDto);
            });
        }
        rspData.setRows(fileDtoList);
        rspData.setTotal(fileIPage.getTotal());
        return rspData;
    }

    @Override
    public FileOperationDto selectFile(FileOperationVo fileOperationVo) {
        LambdaQueryWrapper<FileOperation> wrapper = new QueryWrapper<FileOperation>().lambda();
        wrapper.eq(FileOperation::getUid, fileOperationVo.getUid());
        FileOperation fileOperation = sysFileService.getOne(wrapper);
        if(fileOperation != null){
            log.info("cosClientConfigMap {}", cosClientConfigMap);
            FileOperationDto fileDto = new FileOperationDto();
            BeanUtils.copyProperties(fileOperation, fileDto);
            String url = cosClientConfigMap.getDomain() + fileDto.getFileKey();
            log.info("url {} ", url);
            fileDto.setUrl(url);
            return fileDto;
        }
        return null;
    }

    @Override
    public FileOperationDto importFile(MultipartFile multipartFile) {
        if(multipartFile == null || multipartFile.isEmpty()){
            throw new BusinessException(ResultEnum.DATA_NOT_EXIST);
        }
        String type = multipartFile.getContentType();
        //获取原始文件名
        String fileName = multipartFile.getOriginalFilename();
        log.info("扩展名{}", fileName);
        //获取扩展名
        String expandName = FileUtils.getFileSuffixName(fileName);
        if(fileName.equals("blob")){
            expandName = FileEnum.getFileTypeEnumByCode(type).getSuffix();
        }

        //新的文件名
        String newFileName = UUID.randomUUID() + expandName;
        //文件本地保存路径
        String filePath = localSavePath + "/" + newFileName;
        log.info("保存的本地地址{}", filePath);
        File file = new File(filePath);
        try{
            multipartFile.transferTo(file);
        }catch (IOException ioException){
            throw new BusinessException(ResultEnum.UPLOAD_FAIL);
        }
        log.info("文件类型{}", type);
        //上传文件
        String key = minioFileUtils.fileUpload(filePath, type);
        HttpServletRequest httpServletRequest = RequestHolder.getRequest();
        String userType = httpServletRequest.getHeader("userType");
        FileOperation fileOperation = new FileOperation();
        if(UserTypeEnum.WEB_USER.getCode().equals(userType)){
        }else{
            LoginUser loginUser = SecurityUtils.getLoginUser();
            fileOperation.setTenantUid(loginUser.getUser().getTenantUid());
            fileOperation.setCreateUserId(loginUser.getUserId());
        }
        fileOperation.setUid(SnowflakeIdWorker.getSnowflakeIdWorker());
        fileOperation.setFileKey(key);
        fileOperation.setFileSize(multipartFile.getSize());
        fileOperation.setFileType(type);
        fileOperation.setName(newFileName);
        fileOperation.setExpandName(expandName);
        fileOperation.setOldName(fileName);
        fileOperation.setUpdateTime(new Date());
        fileOperation.setCreateTime(new Date());
        fileOperation.insert();
        log.info("文件上传信息{}", JSONObject.toJSONString(fileOperation));
        FileOperationDto fileOperationDto = new FileOperationDto();
        BeanUtils.copyProperties(fileOperation, fileOperationDto);
        fileOperationDto.setUrl( cosClientConfigMap.getDomain() + fileOperation.getFileKey());
        return fileOperationDto;
    }
}
